package com.pig.controller;

import com.pig.file.FilePojo;
import com.pig.file.Image;
import com.pig.service.AccountUserService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制层
 */
@Controller
public class FileController {
    /**
     * 文件上传页面
     * @return
     */
    @RequestMapping("/file")
    public String file(){
        return "file";
    }

    @Autowired
    private Image image;

    @Autowired
    private AccountUserService accountUserService;

    /**
     * 处理前台传入的文件
     */
    @RequestMapping("/file/oneFileUpload")
    public String oneFileUpload(@ModelAttribute("myFile") MultipartFile myFile, HttpServletRequest request, Model model) throws IOException {
        long startTime = System.currentTimeMillis();
        System.out.println("----------进入上传文件--------------");
        System.out.println("文件类型--"+myFile.getContentType());
        System.out.println("文件大小--"+myFile.getSize());
        System.out.println("文件原名称--"+myFile.getOriginalFilename());
        if (!myFile.isEmpty()){
            FileUtils.copyInputStreamToFile(myFile.getInputStream(),new File( "D:",System.currentTimeMillis()+myFile.getOriginalFilename()));
            System.out.println("上传成功");
            // 运行成功之后的时间
            long endTime = System.currentTimeMillis();
            float excTime = (float) (endTime - startTime) / 1000;
            System.out.println("执行时间：" + excTime + "s");
            return "success";

        }
        System.out.println("上传失败");
        // 运行成功之后的时间
        long endTime = System.currentTimeMillis();
        float excTime = (float) (endTime - startTime) / 1000;
        System.out.println("执行时间：" + excTime + "s");
        return "error";
    }


    /**
     * 处理异步前台传入的图片文件
     */

    @RequestMapping(value = "/upload/headImg", method = {RequestMethod.POST})
    @ResponseBody
    public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String prefix="";
        String dateStr="";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);

                String filepath = request.getServletContext().getRealPath("/static") + "a"+ "." + prefix;
                filepath = filepath.replace("\\", "/");
                File files=new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
            }
        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String,Object> map2=new HashMap<String,Object>();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","");
        map.put("data",map2);
        map2.put("src",request.getServletContext().getRealPath("/static") + "a"+ "." + prefix);
        return map;
    }

    /**
     *文件下载
     */
    @RequestMapping("/downloadFile")
    public ResponseEntity<byte[]> downloadsEntity(HttpServletRequest request) throws Exception {
        long startTime = System.currentTimeMillis();
        System.out.println("---------------------------------进入下载模式---------------------------------");
        String path = "D:\\";
        String fileName = "seaPoacher.zip";
        File file = new File(path, fileName);
        if (!file.isFile()) {
            return null;
        }

        InputStream input = new FileInputStream(file);
        byte[] buff = new byte[input.available()]; // 获取文件大小
        input.read(buff);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=" + fileName);
        HttpStatus status = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(buff, headers, status);
        // 运行成功之后的时间
        long endTime = System.currentTimeMillis();
        float excTime = (float) (endTime - startTime) / 1000;
        System.out.println("执行时间：" + excTime + "s");
        return entity;
    }
}
